package tomcat.connector;

import tomcat.connector.facade.RequestFacade;
import tomcat.connector.facade.ResponseFacade;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;

/**
 * 使用门面
 */
public class ServletProcessor {
    URLClassLoader getServletClassLoader() throws MalformedURLException {
        File webroot = new File(ConnectorUtil.WEB_ROOT);
        URL webrootURL = webroot.toURI().toURL();
        return new URLClassLoader(new URL[]{webrootURL});
    }

    Servlet getServlet(URLClassLoader loader,DynamicRequest request) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
        //  /servlet/AqieServlet
        String uri = request.getUri();
        String servletName = uri.substring(uri.lastIndexOf('/'), 1);

        Class servletClass = loader.loadClass(servletName);
        // 使用反射创建新的类实例
        Servlet servlet = (Servlet) servletClass.newInstance();
        return servlet;
    }
    public void process(DynamicRequest request, DynamicResponse response) {
        try {
            URLClassLoader classLoader = getServletClassLoader();
            Servlet servlet = getServlet(classLoader, request);

            RequestFacade requestFacade = new RequestFacade(request);
            ResponseFacade responseFacade = new ResponseFacade(response);

            servlet.service(requestFacade, responseFacade);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
